package com.jushu.storbox.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ShareMoveActivity;
import com.jushu.storbox.actions.FileFolderAction;
import com.jushu.storbox.actions.ShareActions;
import com.jushu.storbox.adapter.ShareFileAdapter;
import com.jushu.storbox.adapter.ShareUplodAdapter;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.CloudPW;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.dialog.MyPopupWindow;
import com.jushu.storbox.view.pulltorefresh.PullDownElasticImp;
import com.jushu.storbox.view.pulltorefresh.PullDownScrollView;
import com.jushu.storbox.view.pulltorefresh.PullDownScrollView.RefreshListener;
import com.jushu.storbox.view.pulltorefresh.ShareScrollView;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

/**
 * 
 * ShareFragment
 * 
 */
public class ShareFragment extends BaseFragment {

	/** ShareFragment TAG */
	public static final String TAG = "ShareFragment";
	private MyPopupWindow pwPopupWindow;
	private View moreView;
	private LayoutInflater mInflater;
	private ShareUplodAdapter adapter = null;
	private MyPopupWindow moveMyPopupWindow;
	private Button move_confirm;
	private Button move_cancel;
	private ListView move_listView;
	private View window_move;
	private int shareFileListID = 0;
	private String fileID;
	private boolean scr_isDraging = false;
	private String shareFileListName = "";
	private List<FileFolderInfo> shareResources;
	private List<FileFolderInfo> moveList = null;
	private List<List<FileFolderInfo>> shareFileList = null;
	private FileFolderInfo sharedItemFolderFileInfo;
	/** activity */
	private Activity activity;

	/** contentView */
	private View contentView;
	/** LinearLayout */
	private LinearLayout share_list_sv_ll;
	/** shareDriveService */
	private ICloudDriveService shareDriveService;

	/** back relativelayout */
	private RelativeLayout getfolderListProgressBar, shareFileListviewLayout;

	/** sharefregment tittle relativelayout */
	private List<String> fileFolderList = null;

	private FileFolderInfo currnetFolderInfo = null;

	private TextView folder_name;

	private String currentFolderName;
	private boolean isSelect = true;
	/** shared for me net state */
	private RelativeLayout fragment_state_re;
	private ShareScrollView shareMyScrollView;
	private PullDownScrollView share_refresh_root;
	private int indexID = 0;
	private boolean isDraging = false;
	private LinearLayout share_loading_ll;
	private final static int PULLDOWNTOREFRESH = 1001;
	private final static int FROMINODE = 1002;
	private final static int SERVERLINKERROR = 1003;
	private final static int ERRORREQUEST = 1004;
	private final static int RESOURCEISNOTEXIST = 1005;
	private final static int FAILEDTOAUTHEN = 1006;
	private static ShareActions actions;
	private static FileFolderAction fileFolderactions;
	private boolean pullFlag = false;
	private ImageView emptyImg;
	private RelativeLayout move_top_re;
	private Handler activityHandler;
	private FileFolderInfo shareInfo;
	private String returnParent = "Share";
	private List<FileFolderInfo> news_List;
	private LinearLayout movenews_lin;
	private String et_folderId = "";
	private FileFolderInfo et_info;
	private LinearLayout shadowLayout;
	private int fromDir = 25;

	public List<FileFolderInfo> getNews_List() {
		return news_List;
	}

	public void setNews_List(List<FileFolderInfo> news_List) {
		this.news_List = news_List;
	}

	/**
	 * onAttach
	 * 
	 * @param activity
	 *            Activity instance
	 */
	@Override
	public void onAttach(Activity activity) {
		LogUtil.i(TAG, "onAttach Activity");
		this.activity = activity;
		setBack(false);

		if (null == getObj()) {
			// System.exit(1);
			PublicTools.restartApp(activity);
		} else {
			Map<String, Object> mp = (Map<String, Object>) getObj();

			if (null != mp.get("activityhandler")) {
				activityHandler = (Handler) mp.get("activityhandler");
			} else {
				PublicTools.restartApp(activity);
			}
			if (null != mp.get("service")) {
				shareDriveService = (ICloudDriveService) mp.get("service");
			} else {
				PublicTools.restartApp(activity);
			}
			shareInfo = (FileFolderInfo) mp.get("share_entity");
			if (null != shareInfo) {
				returnParent = shareInfo.getName();
				Log.d("name001", "share_name:" + returnParent);
			}
		}
		super.onAttach(activity);
	}

	/**
	 * onCreate in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onCreate method");
		IntentFilter shareStateFilter = new IntentFilter(
				Constant.STATE_SHARED_FRO_ME);
		activity.registerReceiver(shareStateReceiver, shareStateFilter);
		super.onCreate(savedInstanceState);
	}

	/**
	 * onCreateView in Fragment
	 * 
	 * @param inflater
	 *            LayoutInflater
	 * @param container
	 *            ViewGroup
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LogUtil.i(TAG, "onCreateView method");
		contentView = LayoutInflater.from(getActivity()).inflate(
				R.layout.share_fragment, null);
		initFindViewById();
		initData();
		initListenser();
		return contentView;
	}

	private void initListenser() {
		share_loading_ll.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

			}
		});
		share_refresh_root.setRefreshListener(new RefreshListener() {
			@Override
			public void onRefresh(PullDownScrollView view) {
				isDraging = true;
				Message msg = new Message();
				if (View.VISIBLE == movenews_lin.getVisibility()) {
					msg.what = 1;
					msg.obj = getNews_List();
					handler.sendMessageDelayed(msg, 310);
				} else {
					msg.what = 10;
					msg.arg2 = PULLDOWNTOREFRESH;
					msg.obj = currnetFolderInfo;
					handler.handleMessage(msg);
				}
				scr_isDraging = true;
			}
		});

	}

	private void initData() {
		if (View.GONE == share_loading_ll.getVisibility()) {
			share_loading_ll.setVisibility(View.VISIBLE);
		}
		share_refresh_root.setPullDownElastic(new PullDownElasticImp(activity));
		share_refresh_root.setRestSpeed(PullDownScrollView.RESETFAST);
		shareMyScrollView.setLayout(share_list_sv_ll);
		share_list_sv_ll.setBackgroundResource(R.color.white);
		// shere_fragment_tittle_text.setText("");
		actions = new ShareActions(activity);
		fileFolderactions = new FileFolderAction(activity);
		fileFolderactions.setSuccessHandler(handler);
		fileFolderactions.setExceptionHandler(handlers);
		Message msg = new Message();
		msg.what = 10;
		msg.obj = shareInfo;
		handler.sendMessageDelayed(msg, 310);
	}

	private void initFindViewById() {
		Log.d("anim0012", "currents[page]:" + contentView);
		share_loading_ll = (LinearLayout) contentView
				.findViewById(R.id.share_loading_ll);
		share_refresh_root = (PullDownScrollView) contentView
				.findViewById(R.id.share_refresh_root);
		share_list_sv_ll = (LinearLayout) contentView
				.findViewById(R.id.share_layout);
		fragment_state_re = (RelativeLayout) contentView
				.findViewById(R.id.fragment_state_re);
		shareMyScrollView = (ShareScrollView) contentView
				.findViewById(R.id.share_scrollview);
		mInflater = (LayoutInflater) getActivity()
				.getApplicationContext()
				.getSystemService(
						getActivity().getApplicationContext().LAYOUT_INFLATER_SERVICE);
		moreView = mInflater.inflate(R.layout.share_window_more, null);
		window_move = mInflater.inflate(R.layout.share_file_window_move, null);
		move_confirm = (Button) window_move.findViewById(R.id.confirm_btn);
		move_cancel = (Button) window_move.findViewById(R.id.canccle_btn);
		getfolderListProgressBar = (RelativeLayout) window_move
				.findViewById(R.id.share_getfolder_list_progressBar_layout);
		shareFileListviewLayout = (RelativeLayout) window_move
				.findViewById(R.id.share_file_listview_layout);
		move_listView = (ListView) window_move.findViewById(R.id.FileList_lv);
		move_top_re = (RelativeLayout) window_move
				.findViewById(R.id.share_file_folder_list_top_re);
		folder_name = (TextView) window_move
				.findViewById(R.id.list_folder_name_tv);
		movenews_lin = (LinearLayout) contentView
				.findViewById(R.id.movenews_lin);
		shadowLayout = (LinearLayout) contentView.findViewById(R.id.shadow_ll);
	}

	/**
	 * onActivityCreated in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onActivityCreated method");
		super.onActivityCreated(savedInstanceState);
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onStart() {
		super.onStart();
	}

	/**
	 * onResume in Fragment
	 */
	@Override
	public void onResume() {
		LogUtil.i(TAG, "onResume method");
		if (!ShareDriveApplication.getInstance()
				.getWifiController().getNetworkState()) {
			if (View.GONE == fragment_state_re.getVisibility()) {
				fragment_state_re.setVisibility(View.VISIBLE);
			}
		} else {
			if (View.VISIBLE == fragment_state_re.getVisibility()) {
				fragment_state_re.setVisibility(View.GONE);
			}
		}
		super.onResume();
	}

	/**
	 * onPause in Fragment
	 */
	@Override
	public void onPause() {
		super.onPause();
	}

	/**
	 * onSaveInstanceState in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

	/**
	 * onStop in Fragment
	 */
	@Override
	public void onStop() {
		super.onStop();
	}

	/**
	 * onDestroy in Fragment
	 */
	@Override
	public void onDestroy() {
		LogUtil.i(TAG, "onDestroy method");
		if (null != shareStateReceiver) {
			activity.unregisterReceiver(shareStateReceiver);
		}
		super.onDestroy();
	}

	/**
	 * onDestroyView in Fragment
	 */
	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	/**
	 * onDetach in Fragment
	 */
	@Override
	public void onDetach() {
		super.onDetach();
	}

	private void showMsgData(List<FileFolderInfo> shareResource, int msgDir) {
		shareMyScrollView.removeAllItem();
		if (FROMINODE == msgDir) {
			currentFolderName = "";
		} else {
			if (null != currentFolderName) {
			} else {
				currentFolderName = "";
			}
		}
		if (null != shareResource && 0 < shareResource.size()) {
			BaseAdapter mAdapter = new ShareFileAdapter(ShareFragment.this,
					activity, shareResource, shareDriveService, handler);
			shareMyScrollView.setAdptor(mAdapter);
			shareMyScrollView.notifyAllItem();
		} else {
			if (0 == share_list_sv_ll.getChildCount()) {
				emptyImg = new ImageView(activity);
				emptyImg.setBackgroundResource(R.mipmap.no_share_file_bg);
				shareMyScrollView.resetList();
				share_list_sv_ll.addView(emptyImg);
			}
		}
		isDraging = true;
		if (scr_isDraging) {
			String lastRefreshTime = PublicTools.longToString(System
					.currentTimeMillis());
			share_refresh_root.setLastUpdateTime(lastRefreshTime);
			share_refresh_root.finishRefresh();
			scr_isDraging = false;
			ShareDriveApplication.getInstance().setScrolling(false);
		}
		if (View.VISIBLE == share_loading_ll.getVisibility()) {
			share_loading_ll.setVisibility(View.GONE);
		}
		setBack(true);
		hideNewsView();
		onDataLoaded();
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
				Message activityMsg = new Message();
				activityMsg.obj = msg.obj;
				activityMsg.what = 1;
				activityHandler.sendMessage(activityMsg);
				break;
			case 0:
				break;
			case 10: // refresh server
				final FileFolderInfo shareInfos = (FileFolderInfo) msg.obj;
				int msgDir = 0;
				msgDir = msg.arg2;
				final int shareBack = msgDir;
				pullFlag = false;
				currnetFolderInfo = shareInfos;
				if (PULLDOWNTOREFRESH != msgDir) {
					if (View.GONE == share_loading_ll.getVisibility()) {
						share_loading_ll.setVisibility(View.VISIBLE);
					}
				} else {
					pullFlag = true;
				}
				isDraging = false;
				boolean isInode = false;
				final List<FileFolderInfo> shareResource = new ArrayList<FileFolderInfo>();
				FileFolderInfo infoEntity = new FileFolderInfo();
				String folderId = "";
				if (null != shareInfos) {
					folderId = shareInfos.getId();
					if (null != shareInfos.getName()) {
						currentFolderName = shareInfos.getName();
					} else {
						currentFolderName = "";
					}
					if (-1 == shareBack) {
						infoEntity = DAOFactory
								.instance(activity)
								.getShareFolderDao()
								.getFolderById(folderId,
										shareInfos.getOwnerBy());
						if (null != infoEntity
								&& null != infoEntity.getParent()
								&& null != infoEntity.getOwnerBy()) {
							infoEntity = DAOFactory
									.instance(activity)
									.getShareFolderDao()
									.getFolderById(infoEntity.getParent(),
											infoEntity.getOwnerBy());

							if (null != infoEntity
									&& null != infoEntity.getId()) {
								folderId = infoEntity.getId();
								currnetFolderInfo = infoEntity;
								if (null != infoEntity.getName()) {
									currentFolderName = infoEntity.getName();
								} else {
									currentFolderName = "";
								}

							} else {
								isInode = true;
							}
						} else {
							currnetFolderInfo = null;
							isInode = true;
						}
					}
				} else {
					isInode = true;
				}
				if (isInode) {

					final long DBMills = DAOFactory.instance(activity)
							.getShareINodeDao()
							.getLastUpdateTime(activity, "0");
					String time = PublicTools.longToString(DBMills);
					share_refresh_root.setLastUpdateTime(time);

					if (null != shareDriveService) {
						if (0 != DBMills) {
							if (!pullFlag) {

								new Thread(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										getBaseShareResourceFromDB(shareResource);
									}
								}).start();
							}
						}
						new Thread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								long currentMills = System.currentTimeMillis();
								if (ClientConfig.REFRESH_TIME < currentMills
										- DBMills
										|| pullFlag || DBMills == 0) {
									int dir = UiConstant.DIR_CODE_25;
									if (0 == DBMills) {
										dir = UiConstant.DIR_CODE_1;
									}
									if (pullFlag) {
										dir = UiConstant.DIR_CODE_1;
									}
									actions.getBaseShareResourceFromServer(
											shareDriveService,
											handlers, handler, dir);
								}
							}
						}).start();
					}
				} else {
					if (null != shareDriveService) {
						long DBMills = 0l;
						long currentMills = System.currentTimeMillis();
						if (null != shareInfos.getiNodeId()) {
							folderId = shareInfos.getiNodeId();
							DBMills = DAOFactory
									.instance(activity)
									.getShareFolderDao()
									.getLastRefreshTime(
											shareInfos.getOwnerBy(), folderId);
							if (1000 * 60 * 10 < currentMills - DBMills) {
								FileFolderInfo updataFolder = new FileFolderInfo();
								updataFolder.setId(shareInfos.getiNodeId());
								updataFolder
										.setOwnerBy(shareInfos.getOwnerBy());
								updataFolder.setName(shareInfos.getName());
								updataFolder.setLastRefreshTime(System
										.currentTimeMillis());
								DAOFactory
										.instance(activity)
										.getShareFolderDao()
										.insertOrUpdateFolder(activity,
												updataFolder);
							}
						} else {
							DBMills = DAOFactory
									.instance(activity)
									.getShareFolderDao()
									.getLastRefreshTime(
											shareInfos.getOwnerBy(), folderId);
						}
						String time = PublicTools.longToString(DBMills);
						share_refresh_root.setLastUpdateTime(time);
						final long innerCurrentMills = currentMills;
						final long innerDBMills = DBMills;
						final String resourceId = folderId;
						if (0 != DBMills) {
							if (!pullFlag) {
								new Thread(new Runnable() {
									String shareResourceId = resourceId;

									public void run() {
										et_folderId = shareResourceId;
										et_info = shareInfos;
										getShareResourceFromDb(shareResource,
												shareInfos, shareResourceId);
									}
								}).start();
							}
						}
						new Thread(new Runnable() {
							public void run() {
								String shareResourceId = resourceId;

								if (ClientConfig.REFRESH_TIME < innerCurrentMills
										- innerDBMills
										|| (PULLDOWNTOREFRESH == shareBack)
										|| (0 == innerDBMills)) {
									int dir = UiConstant.DIR_CODE_25;
									if (0 == innerDBMills) {
										dir = UiConstant.DIR_CODE_1;
									}
									if (pullFlag) {
										dir = UiConstant.DIR_CODE_1;
									}
									actions.getShareResourceFromServer(
											shareInfos, shareResourceId,
											shareDriveService,
											handlers, handler,dir);

								}
							}
						}).start();
					}
				}
				break;
			case 1:// refresh and display res list
				int msgDirs = 0;
				msgDirs = msg.arg2;
				shareResources = (List<FileFolderInfo>) msg.obj;
				showMsgData(shareResources, msgDirs);
				break;
			case 25:
				// if (shareDriveService.getShareResourceIsChange()) {
				if (FROMINODE == msg.arg2) {
					if (shareDriveService.getInodeResourceIsChange()) {
						getNewsView();
						setNews_List((List<FileFolderInfo>) msg.obj);
					}
				} else {
					if (shareDriveService.getShareResourceIsChange()) {
						getNewsView();
						setNews_List((List<FileFolderInfo>) msg.obj);
					}
				}
				break;
			case 2:
				// add view into page
				break;
			case FAILEDTOAUTHEN:// 401
				// relogin
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (null != shareDriveService) {
							shareDriveService.loginIn(
									PublicTools.getLoginUserName(activity),
									PublicTools.getLoginUserPassFail(activity),
									null);
						}
					}
				}).start();
				break;
			case SERVERLINKERROR:// 901
				Toast.makeText(
						activity,
						activity.getString(R.string.allfile_network_inavailable),
						Toast.LENGTH_SHORT).show();

				break;
			case ERRORREQUEST:// 400
				break;
			case RESOURCEISNOTEXIST://
				Toast.makeText(
						activity,
						activity.getString(R.string.allfile_filefolder_no_exist),
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	private BroadcastReceiver shareStateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int code = intent.getIntExtra("statecode", -1);
			if (0 == code) {
				fragment_state_re.setVisibility(View.VISIBLE);
			}
			if (1 == code) {
				fragment_state_re.setVisibility(View.GONE);
			}
		}
	};

	private void getBaseShareResourceFromDB(List<FileFolderInfo> shareResource) {

		shareResource = shareDriveService.getBaseDBShareResourceList("0",
				ShareDriveApplication.getInstance().getWnerID(), "desc", 1000,
				0, "modified_at");
		Message listMsg = new Message();
		listMsg.what = 1;
		listMsg.arg2 = FROMINODE;
		listMsg.obj = shareResource;
		handler.sendMessage(listMsg);
	}

	private void getShareResourceFromDb(List<FileFolderInfo> shareResource,
			FileFolderInfo shareInfos, String folderId) {

		shareResource = shareDriveService.getDBShareResourceList(folderId,
				shareInfos.getOwnerBy(), true, 1000, 0, "modifiedAt");
		Message listMsg = new Message();
		listMsg.what = 1;
		listMsg.obj = shareResource;
		handler.sendMessage(listMsg);

	}

	Handler handlers = new Handler() {
		public void handleMessage(Message msg) {

			String code = (String) msg.obj;
			int codeDir = msg.arg1;
			if (View.VISIBLE == share_loading_ll.getVisibility()) {
				share_loading_ll.setVisibility(View.GONE);
			}
			if (ShareDriveApplication.getInstance().isScrolling()) {
				share_refresh_root.finishRefresh();
				ShareDriveApplication.getInstance().setScrolling(false);
			}
			if (false == isDraging) {
				isDraging = true;
			}
			setBack(true);
			onDataLoaded();
			switch (msg.what) {
			case ExceptionConstant.access_internet_Failed:
				// Toast.makeText(
				// activity,
				// activity.getResources().getString(
				// R.string.network_problem), Toast.LENGTH_SHORT)
				// .show();
				switch (codeDir) {
				case ClientConfig.SENDFROMGETSHARERESOURCE:
					// List<FileFolderInfo> shareResource = new
					// ArrayList<FileFolderInfo>();
					// Log.d("shareList", "SENDFROMGETSHARERESOURCE"
					// + currnetFolderInfo.getId());
					// getShareResourceFromDb(shareResource, et_info,
					// et_folderId);
					// et_info = null;
					// et_folderId = "";
					break;
				case ClientConfig.SENDFROMGETSHAREBASERESOURCE:
					List<FileFolderInfo> shareBaseResource = new ArrayList<FileFolderInfo>();
					getBaseShareResourceFromDB(shareBaseResource);
					break;
				}
				break;
			/** 901 server fail*/
			case ExceptionConstant.access_Server_Failed:
				Toast.makeText(
						activity,
						activity.getString(R.string.loginwait_activity_server_not_response)
								+ "(" + msg.what + ")", Toast.LENGTH_SHORT)
						.show();
				switch (codeDir) {

				case ClientConfig.SENDFROMGETSHARERESOURCE:
//					List<FileFolderInfo> shareResource = new ArrayList<FileFolderInfo>();
//					getShareResourceFromDb(shareResource, et_info, et_folderId);
//					et_info = null;
//					et_folderId = "";
					break;
				case ClientConfig.SENDFROMGETSHAREBASERESOURCE:
//					List<FileFolderInfo> shareBaseResource = new ArrayList<FileFolderInfo>();
//					getBaseShareResourceFromDB(shareBaseResource);
					break;
				}
				break;
			/** 401 auth or disable*/
			case ExceptionConstant.Authorized_Code:
				switch (codeDir) {
				case ClientConfig.SENDFROMLOGIN:
					if (ExceptionConstant.clientunauthorized
							.equalsIgnoreCase(code)) {
						if (null != shareDriveService) {
							shareDriveService.clearCloudDriveCache(null);
							Toast.makeText(
									activity,
									getResources().getString(
											R.string.device_disable),
									Toast.LENGTH_SHORT).show();
						}
					}else if(ExceptionConstant.unauthorized.equalsIgnoreCase(code)){
						Toast.makeText(activity,
								getResources().getString(R.string.passwordiswrong),
								Toast.LENGTH_SHORT).show();
					}
					break;
				default:
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.device_disable),
							Toast.LENGTH_SHORT).show();
					break;
				}
				returnToLoginActivity();
				break;
			/** 409 exist same res */
			case ExceptionConstant.conflict_Code:
				Toast.makeText(activity,
						getResources().getString(R.string.exist_same_resource),
						Toast.LENGTH_SHORT).show();
				break;
			/** 403 forbidden or userlocked */
			case ExceptionConstant.Forbidden_Code:

				if (ExceptionConstant.UserLocked.equalsIgnoreCase(code)) {
					if (null != shareDriveService) {
						shareDriveService.clearCloudDriveCache(null);
						Toast.makeText(
								activity,
								getResources().getString(
										R.string.login_locked_window_message),
								Toast.LENGTH_SHORT).show();
					}
				}else if (ExceptionConstant.forbidden.equalsIgnoreCase(code)) {
						Toast.makeText(
								activity,
								getResources().getString(
										R.string.obj_forbidden),
								Toast.LENGTH_SHORT).show();
				}
				break;
			/** 507  */
			case ExceptionConstant.insufficient_storage_Code:

				break;
			/** 500 server error */
			case ExceptionConstant.InternalServerError_Code:
				Toast.makeText(activity,
						getResources().getString(R.string.server_inner_error),
						Toast.LENGTH_SHORT).show();
				break;
			/** 405 */
			case ExceptionConstant.Method_Code:
				Toast.makeText(activity,
						getResources().getString(R.string.access_is_forbiden),
						Toast.LENGTH_SHORT).show();
				break;
			/** 400 error req or error param or invalid range */
			case ExceptionConstant.Request_Code:

				if (ExceptionConstant.BadRequest.equalsIgnoreCase(code)) {
					Toast.makeText(activity,
							getResources().getString(R.string.request_error),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.invalid_paramter
						.equalsIgnoreCase(code)) {
					Toast.makeText(activity,
							getResources().getString(R.string.param_error),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.invalid_range.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.part_is_not_availible),
							Toast.LENGTH_SHORT).show();
				} else {
				}
				break;
			/** 412 */
			case ExceptionConstant.requests_Code:

				if (ExceptionConstant.too_many_requests.equalsIgnoreCase(code)) {
					Toast.makeText(activity,
							getResources().getString(R.string.requset_to_much),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.precondition_failed
						.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.request_preview_conditions_error),
							Toast.LENGTH_SHORT).show();
				}
				break;
			/** 404 res is not exist */
			case ExceptionConstant.Resource_Code:
				if (ExceptionConstant.NoFound.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.resource_is_not_exist),
							Toast.LENGTH_SHORT).show();
					switch (codeDir) {
					case ClientConfig.SENDFROMGETSHARERESOURCE:
						String parentFolderId = "0";
						if (null != currnetFolderInfo.getParent()) {
							parentFolderId = currnetFolderInfo.getParent();
						}
						if ("0".equals(parentFolderId)) {
							actions.getBaseShareResourceFromServer(
									shareDriveService,
									handlers, handler, 1);
						} else {
							actions.getShareResourceFromServer(
									currnetFolderInfo,
									parentFolderId, shareDriveService,
									handlers, handler, 1);
						}
						break;
					case ClientConfig.SENDFROMGETSHAREBASERESOURCE:
						actions.getBaseShareResourceFromServer(
								shareDriveService,
								handlers, handler, 1);
						break;
					}
				} else if (ExceptionConstant.no_such_user.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources()
									.getString(R.string.user_is_not_exist),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.NoSuchFolder.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.resource_is_not_exist),
							Toast.LENGTH_SHORT).show();
					switch (codeDir) {
					case ClientConfig.SENDFROMGETSHARERESOURCE:
						String parentFolderId = "0";
						if (null != currnetFolderInfo.getParent()) {
							parentFolderId = currnetFolderInfo.getParent();
						}
						if ("0".equals(parentFolderId)) {
							actions.getBaseShareResourceFromServer(
									shareDriveService,
									handlers, handler, 1);
						} else {
							actions.getShareResourceFromServer(
									currnetFolderInfo,
									parentFolderId, shareDriveService,
									handlers, handler, 1);
						}
						break;
					case ClientConfig.SENDFROMGETSHAREBASERESOURCE:
						actions.getBaseShareResourceFromServer(
								shareDriveService,
								handlers, handler,  1);
						break;
					}
				} else if (ExceptionConstant.no_such_version
						.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.version_is_not_exist),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.NoSuchLink.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources()
									.getString(R.string.link_is_not_exist),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.LinkNotEffective
						.equalsIgnoreCase(code)) {
					Toast.makeText(activity,
							getResources().getString(R.string.link_is_effect),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.LinkExpired.equalsIgnoreCase(code)) {
					Toast.makeText(activity,
							getResources().getString(R.string.link_is_disable),
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.resource_is_not_exist),
							Toast.LENGTH_SHORT).show();
				}
				break;
			/** 503 Service Unavailable */
			case ExceptionConstant.Service_Unavailable:
				Toast.makeText(
						activity,
						getResources().getString(
								R.string.serve_is_not_availible),
						Toast.LENGTH_SHORT).show();
				break;
			/** 417 */
			case ExceptionConstant.transaction_Code:
				if (ExceptionConstant.transactionCommitError
						.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.request_preview_conditions_error),
							Toast.LENGTH_SHORT).show();
				} else if (ExceptionConstant.transactionRollbackError
						.equalsIgnoreCase(code)) {
					Toast.makeText(
							activity,
							getResources().getString(
									R.string.request_preview_conditions_error),
							Toast.LENGTH_SHORT).show();
				}
				break;
//			case 1000:
//				if (null != shareDriveService) {
//					shareDriveService.upgradeCloudDrive(null);
//				}
//				break;
			/** default */
			case 0://
				if(msg.arg1 == 1020){
					if(msg.arg2 == Constant.SAVE_TO_ONEBOX_fail){
						Toast.makeText(
								activity,
								getResources().getString(
										R.string.allfile_filefolder_no_exist),
										Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(
								activity,
								getResources().getString(
										R.string.share_fragment_move_file_error),
										Toast.LENGTH_SHORT).show();
					}
				}
				break;
			default:
				break;
			}
		};
	};

	private void returnToLoginActivity() {
		Intent intent = new Intent();
		intent.setClass(activity, LoginActivity.class);
		activity.startActivity(intent);
		activity.finish();
	}

	public void MoreButton(View view, int indexID, FileFolderInfo itemInfo) {
		if (PublicTools.mdmRootCheck()) {
			return;
		} else {
			this.indexID = indexID;
			showMoreWoindow(view, itemInfo);
		}

	}

	private void showMoreWoindow(final View view, FileFolderInfo itemInfo) {
		CloudPW pwPopupWindow = new CloudPW(activity);
		View conventView = pwPopupWindow
				.initCloudPW(R.layout.share_window_more);
		PopupWindow mPopupWindow = pwPopupWindow.getPw();
		mPopupWindow.showAsDropDown(view);
		LinearLayout share_window_more_move_ll = (LinearLayout) conventView
				.findViewById(R.id.share_window_more_move_ll);
		LinearLayout share_window_more_delete_ll = (LinearLayout) conventView
				.findViewById(R.id.share_window_more_delete_ll);
		if (null == itemInfo.getiNodeId()) {
			share_window_more_delete_ll.setVisibility(View.GONE);
		}
		share_window_more_move_ll
				.setOnClickListener(new MoreWindowsButtonListener(itemInfo,
						mPopupWindow));
		share_window_more_delete_ll
				.setOnClickListener(new MoreWindowsButtonListener(itemInfo,
						mPopupWindow));
		// pwPopupWindow = new MyPopupWindow();
		// PopupWindow pw = pwPopupWindow.initPopupWindow(moreView,
		// LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// pw.setOnDismissListener(new OnDismissListener() {
		// @Override
		// public void onDismiss() {
		// view.setBackgroundResource(R.drawable.more_nopitch);
		// }
		// });
		// int[] loction = new int[2];
		// view.getLocationOnScreen(loction);
		// int more_img_y = loction[1];
		// pw.setOutsideTouchable(true);
		// pw.setBackgroundDrawable(new BitmapDrawable());
		// pw.showAtLocation(view, Gravity.TOP | Gravity.RIGHT, 0, more_img_y
		// + (view.getHeight() / 2 + 20));
		// view.setBackgroundResource(R.drawable.more_pitch);
	}

	private class MoreWindowsButtonListener implements OnClickListener {
		PopupWindow mPopupWindow = null;

		public MoreWindowsButtonListener(FileFolderInfo itemInfo,
				PopupWindow mPopupWindow) {
			// TODO Auto-generated constructor stub
			sharedItemFolderFileInfo = itemInfo;
			this.mPopupWindow = mPopupWindow;
		}

		@Override
		public void onClick(View arg0) {
			if (arg0.getId() == R.id.share_window_more_move_ll) {
				if (null != mPopupWindow) {
					mPopupWindow.dismiss();
				}
				if (ShareDriveApplication.getInstance()
						.getWifiController().getNetworkState()) {
					Intent intent = new Intent(activity,
							ShareMoveActivity.class);
					startActivityForResult(intent, 0);
				} else {
					Toast.makeText(
							activity,
							activity.getString(R.string.clouddrive_mode_without_internet),
							Toast.LENGTH_SHORT).show();
				}
			} else if (arg0.getId() == R.id.share_window_more_delete_ll) {
				if (null != mPopupWindow) {
					mPopupWindow.dismiss();
				}
				if (ShareDriveApplication.getInstance()
						.getWifiController().getNetworkState()) {
					final ClouddriveDialog delete = new ClouddriveDialog(
							activity, R.style.dialog_upload,
							R.layout.dialog_filedelete);
					View conventView = delete.getConventView();
					Button dialog_cancal = (Button) conventView
							.findViewById(R.id.dialog_add_file_cancal_bt);

					Button dialog_OK = (Button) conventView
							.findViewById(R.id.dialog_add_file_ok_bt);

					TextView dialog_prompt_tv = (TextView) conventView
							.findViewById(R.id.dialog_prompt_tv);
					dialog_prompt_tv
							.setText(activity
									.getString(R.string.tip_user_exit_share));
					dialog_cancal
							.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									delete.dismiss();
								}
							});
					dialog_OK.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							delete.dismiss();
							new Thread(new Runnable() {
								@Override
								public void run() {
									actions.deleteINodeFileOrFolder(
											shareDriveService,
											handlers, pageHandler,
											sharedItemFolderFileInfo);
								}
							}).start();
						}
					});
					delete.show();
				} else {
					Toast.makeText(
							activity,
							activity.getString(R.string.clouddrive_mode_without_internet),
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) {
		case 1:// confirm
			Bundle bundle = data.getBundleExtra("moverespnse");
			FileFolderInfo fileFolderInfo = null;
			if (null != bundle) {
				fileFolderInfo = (FileFolderInfo) bundle.getSerializable("parentInfo");
			}
			
			//save to root folder
			if (null == fileFolderInfo) {
				fileFolderInfo = new FileFolderInfo();
				fileFolderInfo.setId("0");
				fileFolderInfo.setName(getString(R.string.my_cloud_drive));
			}
			
			final FileFolderInfo innerParenttemp = fileFolderInfo;
			
			new Thread(new Runnable() {
				@Override
				public void run() {
					if (null != sharedItemFolderFileInfo) {
						if (sharedItemFolderFileInfo.getIsFile() == 1) {
							actions.shareCopyFile(shareDriveService,
									handlers, pageHandler, 
									innerParenttemp, sharedItemFolderFileInfo);
						} else {
							actions.shareCopyFolder(
									shareDriveService,
									handlers, pageHandler, 
									innerParenttemp, sharedItemFolderFileInfo);
						}
					}
				}
			}).start();
			break;
		case 2:// cancel
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void getData(final FileFolderInfo folder) {
		getfolderListProgressBar.setVisibility(View.VISIBLE);
		shareFileListviewLayout.setVisibility(View.GONE);
		new Thread(new Runnable() {
			public void run() {
				try {
					if (null != shareDriveService) {
						moveList = shareDriveService.getMoveFolderList(
								folder.getOwnerId(),
								folder.getId(), "DESC", 1000, 0, "modifiedAt");
					}
					shareFileList.add(moveList);
					Message message = new Message();
					message.what = 1;
					moveHandler.sendMessage(message);
				} catch (ClientException e) {
					// Toast.makeText(getApplicationContext(),e.getStatusCode()
					// ,Toast.LENGTH_LONG).show();
					Message message = new Message();
					message.what = 5;
					Bundle bundle = new Bundle();
					bundle.putInt("loadCode", e.getStatusCode());
					message.setData(bundle);
					moveHandler.sendMessage(message);
				}
			}
		}).start();
	}

	private Handler moveHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (shareFileList.get(shareFileListID) != null) {
					adapter = new ShareUplodAdapter(getActivity()
							.getApplicationContext(),
							shareFileList.get(shareFileListID));
					move_listView.setAdapter(adapter);
					getfolderListProgressBar.setVisibility(View.GONE);
					shareFileListviewLayout.setVisibility(View.VISIBLE);
					isSelect = true;
					move_listView
							.setOnItemClickListener(new FileListItemClickListener());
					break;
				} else {
					break;
				}
			case 8:
				shareFileList.clear();
				folder_name.setText(getActivity().getResources().getString(
						R.string.share));
				pwPopupWindow.closePopupWindow();
				break;
			}
		}
	};

	private class FileListItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (isSelect) {
				getData(shareFileList.get(shareFileListID).get(arg2));
				fileID = shareFileList.get(shareFileListID).get(arg2).getId();
				folder_name.setText(shareFileList.get(shareFileListID)
						.get(arg2).getName());
				shareFileListName = shareFileList.get(shareFileListID)
						.get(arg2).getName();
				fileFolderList.add(shareFileListName);
				shareFileListID += 1;
				isSelect = false;
			}
		}
	}

	private class ButtonClickListener implements OnClickListener {
		public ButtonClickListener() {
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onClick(View arg0) {
			if (arg0.equals(move_cancel)) {
				shareFileList.clear();
				shareFileListID = 0;
				folder_name.setText(getActivity().getApplicationContext()
						.getResources().getString(R.string.share));
				moveMyPopupWindow.closePopupWindow();
			} else if (arg0.equals(move_top_re)) {

				if (isSelect) {
					if (shareFileListID != 0) {
						if (shareFileList.size() > 0) {
							shareFileList.remove(shareFileList.size() - 1);
							fileFolderList.remove(fileFolderList.size() - 1);
							shareFileListID -= 1;
							if (fileFolderList.size() > 0) {
								folder_name.setText(fileFolderList
										.get(shareFileListID));
							} else if (shareFileListID == 0) {
								folder_name.setText(getActivity()
										.getResources().getString(
												R.string.share));
							}
							adapter = new ShareUplodAdapter(getActivity(),
									shareFileList.get(shareFileListID));
							move_listView.setAdapter(adapter);
							move_listView
									.setOnItemClickListener(new FileListItemClickListener());
						} else {

						}
					}
				}

			}
		}
	}

	@Override
	public void refreshListFromServer() {
		// TODO Auto-generated method stub
		Message msg = new Message();
		msg.what = 10;
		msg.obj = currnetFolderInfo;
		handler.sendMessage(msg);
	}
	
	public void refreshFileListUI(){
//		shareMyScrollView.getAdptor().notifyDataSetChanged();
	}

	@Override
	public String getParent() {
		// TODO Auto-generated method stub
		return returnParent;
	}

	private void getNewsView() {
		if (View.GONE == movenews_lin.getVisibility()) {
			movenews_lin.setVisibility(View.VISIBLE);
		}
	}

	private void hideNewsView() {
		if (View.VISIBLE == movenews_lin.getVisibility()) {
			movenews_lin.setVisibility(View.GONE);
		}
	}

	@Override
	public void onDataLoaded() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (null != activityHandler) {
					Message dissMissMsg = new Message();
					dissMissMsg.what = 12;
					dissMissMsg.arg1 = 1;
					activityHandler.sendMessageDelayed(dissMissMsg, 100);
				}
			}
		}).start();
	}

	//
	private Handler pageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Bundle bundle = msg.getData();
				FileFolderInfo entity = (FileFolderInfo) bundle
						.getSerializable("sharedItemInfo");
				shareResources.remove(entity.getItemView());
				BaseAdapter sharedAdapter = new ShareFileAdapter(
						ShareFragment.this, activity, shareResources,
						shareDriveService, handler);
				// BaseAdapter mAdapter = new MyFileListAdapter(activity,
				// handler, shareResources, shareDriveService);
				shareMyScrollView.setAdptor(sharedAdapter);
				shareMyScrollView.removeItem(entity.getItemView());
				Toast.makeText(activity,
						getString(R.string.operate_success),
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(activity,
						getString(R.string.operate_fail),
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				if (null != msg.obj) {
					final FileFolderInfo innerParent = (FileFolderInfo) msg.obj;
					Toast.makeText(
							activity,
							activity.getString(R.string.share_fragment_move_save_file)
									+ innerParent.getName(), Toast.LENGTH_SHORT)
							.show();
					new Thread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							fileFolderactions.getAllFileListFromServer(
									innerParent.getOwnerId(),
									innerParent.getId(), shareDriveService,
									-200);
						}
					}).start();
				}
				break;
			}

		}
	};

	public ShareScrollView getShareScrollView() {
		return this.shareMyScrollView;
	}

	@Override
	public PullDownScrollView getPullDownScrollView() {
		return this.share_refresh_root;
	}

	@Override
	public View getConventview() {
		// TODO Auto-generated method stub
		return contentView;
	}

	@Override
	public LinearLayout getShawodLayout() {
		// TODO Auto-generated method stub
		return this.shadowLayout;
	}

	@Override
	public int getDir() {
		// TODO Auto-generated method stub
		return this.fromDir;
	}

	@Override
	public void setDir(int dir) {
		// TODO Auto-generated method stub
		this.fromDir = dir;
	}
}
